using Services;
using UnityEngine;

public class LifetimeController : MonoBehaviour
{
    public float time;
    private float timer;
    private EventSystem eventSystem;

    private void Awake()
    {
        eventSystem = ServiceLocator.Get<EventSystem>();
    }

    private void OnEnable()
    {
        timer = 0f;
        eventSystem.AddListener<float>(EEvent.Tick, Tick);
    }

    private void OnDisable()
    {
        eventSystem.RemoveListener<float>(EEvent.Tick, Tick);
    }

    private void Tick(float t)
    {
        timer += t;
        if (timer >= time)
        {
            MyObject obj = GetComponent<MyObject>();
            if (obj != null)
                obj.Recycle();
            else
                Destroy(gameObject);
        }
    }
}
